package com.smart.job;

import com.smart.pojo.Finance;
import com.smart.pojo.Salary;
import com.smart.resp.UserResp;
import com.smart.service.IFinanceService;
import com.smart.service.ISalaryService;
import com.smart.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
public class SalaryJob {

    @Autowired
    ISalaryService salaryService;
    @Autowired
    IUserService userService;

    @Autowired
    IFinanceService financeService;

    /**
     * 每月1号凌晨生成当月员工薪资记录
     */
    @Scheduled(cron = "0 0 0 1 * ?")
//    @Scheduled(cron = "0/5 * * * * ?")  //每五秒
//    @Scheduled(cron = "0 0/1 * * * ?")  //每1分钟
    public void createSalary() {
        List<UserResp> userList = userService.queryAll();
        List<Salary> salaries = new ArrayList<>();
        for (UserResp userResp : userList) {
            Salary salary = new Salary();
            salary.setUserId(userResp.getId());
            salary.setBaseAmount(userResp.getBaseAmount());
            salary.setSalaryDate(LocalDateTime.now());
            salary.setStatus(0);
            salaries.add(salary);
        }
        boolean rs = salaryService.saveBatch(salaries);
    }

    /**
     * 每月15号凌晨4点发放上月工资
     */
    @Scheduled(cron = "0 0 4 15 * ?")
    public void paySalary() {
        List<Salary> salaries = salaryService.queryNotPaySalaries();
        Finance finance = new Finance();
        finance.setType(0);
        finance.setAmount(new BigDecimal(0));
        for (Salary salary : salaries) {
            finance.setAmount(finance.getAmount()
                    .add(salary.getBaseAmount())
                    .add(salary.getRdAmount())
                    .add(salary.getBonus())
                    .add(salary.getReimbursementAmount())
                    .add(salary.getSalesAmount())
                    .subtract(salary.getPenalty())
                    .subtract(salary.getLeaveAmount()));
            salary.setStatus(1);
        }
        boolean save = financeService.save(finance);
        boolean rs = salaryService.saveBatch(salaries);
    }
}
